package com.tanhua.dubbo.server.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.Voice;
import com.tanhua.dubbo.server.service.IdService;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;


@Service(version = "1.0.0")
@Slf4j
public class VoiceApiImpl implements VoiceApi {
    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;



    /**
     * 发布音频
     *
     * @param voice
     * @return
     */
    @Override
    public String saveVoice(Voice voice) {
        try {
            //校验,检测音频的用户id和音频地址是否为null
            if (!ObjectUtil.isAllNotEmpty(voice.getUserId(), voice.getVoiceUrl())) {
                return null;
            }

            //设置id
            voice.setId(ObjectId.get());
            voice.setVid(idService.createId(IdType.VOICE));
            String redisKey = "TANHUA_Voice";

            //发布时间
            voice.setCreated(System.currentTimeMillis());

            //保存到MongoDB中
            mongoTemplate.save(voice);

            //在redis中保存voice的最大长度
            redisTemplate.opsForValue().set(redisKey,voice.getVid().toString());

            return voice.getId().toHexString();
        } catch (Exception e) {
            log.error("音频发布失败 voice = " + voice, e);
        }
        return null;
    }

    /**
     * 接收语音
     * @param userId
     * @return
     */
    @Override
    public Voice queryVoiceById(Long userId) {
        String idKey = "TANHUA_ID_" + IdType.VOICE.toString();
        Integer maxVid = Integer.valueOf(redisTemplate.opsForValue().get(idKey));
        int voiceVid = RandomUtil.randomInt(0, maxVid) + 1;
        Query query = Query.query(Criteria.where("vid").is(voiceVid));
        Voice voice = mongoTemplate.findOne(query, Voice.class);
        if (ObjectUtil.isNotEmpty(voice)) {
            //查询一次,可查询持续减一
            String redisKey = "REMAINING_TIMES";
            String hashCountKey = "COUNT_" + userId.toString();
            redisTemplate.opsForHash().increment(redisKey, hashCountKey, -1);
            return voice;
        }
        return null;
    }

    @Override
    public Integer getRemainingTimes(Long userId) {
        //查询用户今天剩余次数
        String today = DateUtil.today();
        Long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
        Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();
        Integer count = 10;
        String redisKey = "REMAINING_TIMES";
        String hashCountKey = "COUNT_" + userId.toString();
        String hashTimeKey = "TIME_" + userId.toString();
        //上次查询时间
        Long lastQuery = Convert.toLong(redisTemplate.opsForHash().get(redisKey, hashTimeKey));
        //第一次使用该功能,新建键值
        if (ObjectUtil.isEmpty(lastQuery)) {
            lastQuery = System.currentTimeMillis();
            redisTemplate.opsForHash().put(redisKey, hashTimeKey, Convert.toStr(lastQuery));
            redisTemplate.opsForHash().put(redisKey, hashCountKey, "10");
        }
        //上次查询时间小于今天的最小时间则判定为新的一天,重置次数
        if (lastQuery < minDate) {
            redisTemplate.opsForHash().put(redisKey, hashCountKey, "10");
            lastQuery = System.currentTimeMillis();
            redisTemplate.opsForHash().put(redisKey, hashTimeKey, Convert.toStr(lastQuery));
            return count;
        }
        //在今天的时间范围内
        if (minDate < lastQuery && lastQuery < maxDate) {
            count = Convert.toInt(redisTemplate.opsForHash().get(redisKey, hashCountKey));
            redisTemplate.opsForHash().put(redisKey, hashTimeKey, Convert.toStr(System.currentTimeMillis()));
            if (count <= 0) {
                return 0;
            }
        }
        return count;
    }

}
